import { Eventable } from "./Eventable.js";

export enum ByWhat {
    NONE = 0x00,
    MANUAL = 0x01,
    CODE = 0x02,
    ALL = 0x03
}

export class StateManager extends Eventable {
    #pause: ByWhat;
    #over: boolean = false;

    constructor() {
        super();
        this.#pause = ByWhat.NONE;
    }

    get isPaused(): boolean {
        return !!(this.#pause & ByWhat.ALL);
    }

    get isPausedByManual(): boolean {
        return !!(this.#pause & ByWhat.MANUAL);
    }

    get isRestartable(): boolean {
        return this.isPausedByManual || this.isOver;
    }

    get isOver(): boolean {
        return this.#over;
    }

    pause(byWhat: ByWhat): void {
        const isPaused = this.isPaused;
        this.#pause |= byWhat;
        if (!isPaused) {
            this.trigger("pause");
        }
    }

    resume(byWhat: ByWhat): void {
        if (this.isOver) {
            return;
        }
        const isPaused = (this.#pause &= ~byWhat) & ByWhat.ALL;
        if (!isPaused) {
            this.trigger("resume");
        }
    }

    restart(): void {
        this.#over = false;
        this.trigger("restart");
        this.resume(ByWhat.ALL);
    }

    over(): void {
        this.#over = true;
        this.pause(ByWhat.ALL);
    }
}
